/*
 * Copyright (C) 2025 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package top.xbaistack.controller;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.xbaistack.game.Player;
import top.xbaistack.game.PlayerInfo;
import top.xbaistack.game.Role;
import top.xbaistack.game.Room;
import top.xbaistack.utils.Assert;
import top.xbaistack.ws.RoomManager;

/**
 * 用于提供创建游戏房间的接口
 *
 * @author xbaistack
 * @since 2025/03/25
 */
@RestController
@RequestMapping("/room")
public class RoomController {

    @PostMapping("/create")
    public PlayerInfo createRoom(String role, String setup, boolean priority) {
        Assert.isTrue(Role.isValid(role), "角色无效：" + role);
        Assert.notBlank(setup, "请输入棋盘规格！");
        Assert.isTrue(setup.contains(":"), "棋盘规格错误（如：5:5 表示生成一个 5×5 的棋盘）");
        // 棋盘设置规格：x:y，表示横向纵向多少个格子。
        String[] parts = StringUtils.split(setup, ":");
        int rows = NumberUtils.toInt(parts[ 0 ]);
        int cols = NumberUtils.toInt(parts[ 1 ]);
        // 创建游戏房间
        Room room = RoomManager.newRoom(rows, cols);
        // 玩家：我
        Player me = new Player(Role.of(role));
        me.setFrozen(!priority);
        // 玩家：对手
        Player opponent = new Player(me.getRole().anotherRole());
        opponent.setFrozen(priority);
        // 将玩家添加到房间里
        room.addPlayer(me);
        room.addPlayer(opponent);
        // 返回给前端玩家信息
        return new PlayerInfo(room.getId(), me.getId(), opponent.getId());
    }

}
